package com.zhibang.util;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云OSS图片上传工具类
 */
public class OSSImageUploader {
    // 配置参数
    private static final String accessKeyId = "LTAI5tEqWWaFTb9xYG42g5d5";
    private static final String accessKeySecret = "tg8ZbqYnqzxzpNrvAMo6k03v5mR5A8";
    private static OSS ossClient;
    private static final String bucketName = "travel-lewin";
    private static final String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    private static final String region = "cn-beijing";
    private static final String accessDomain = "https://" + bucketName + "." + endpoint.replace("https://", "");; // 访问域名，如：https://your-bucket.oss-cn-beijing.aliyuncs.com

    static {
        // 创建凭证提供者
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        // 配置客户端
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        conf.setSignatureVersion(SignVersion.V4);
        // 创建OSSClient实例
        ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(conf)
                .region(region)
                .build();
    }

    /**
     * 上传本地图片文件
     * @param file 本地图片文件
     * @param targetDir OSS目标目录，如："images/"（以/结尾）
     * @return 图片访问URL
     */
    public static String uploadImage(File file, String targetDir) throws IOException {
        try (InputStream inputStream = new FileInputStream(file)) {
            // 生成唯一文件名
            String fileName = file.getName();
            String objectName = targetDir + fileName;
            // 上传文件
            ossClient.putObject(bucketName, objectName, inputStream);
            // 返回访问URL
            return accessDomain + "/" + objectName;
        }
    }
    public static String uploadImage(InputStream is, String fileName, String targetDir) throws IOException {
        String objectName = targetDir + fileName;
        // 上传文件
        ossClient.putObject(bucketName, objectName, is);
        // 返回访问URL
        return accessDomain + "/" + objectName;
    }

    /**
     * 删除图片
     * @param objectName OSS对象名称，如："images/abc.jpg"
     */
    public static void deleteImage(String objectName) {
        ossClient.deleteObject(bucketName, objectName);
    }

    /**
     * 关闭OSS客户端
     */
    public static void shutdown() {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

    /**
     * 生成唯一文件名（UUID + 原始文件扩展名）
     */
    private static String generateUniqueFileName(String originalFileName) {
        String extension = "";
        int dotIndex = originalFileName.lastIndexOf('.');
        if (dotIndex > 0) {
            extension = originalFileName.substring(dotIndex);
        }
        return UUID.randomUUID().toString().replace("-", "") + extension;
    }

    // 示例用法
    public static void main(String[] args) {
        try {
            // 示例1：上传本地文件
            File imageFile = new File("C:\\Users\\70884\\Pictures\\logo.jpg.png");
            String imageUrl1 = OSSImageUploader.uploadImage(imageFile, "img/");
            System.out.println("上传成功，访问URL: " + imageUrl1);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端
            OSSImageUploader.shutdown();
        }
    }
}